package com.thinkit.bigdata.web.service.impl.statistics;

import com.google.common.base.Strings;
import com.thinkit.bigdata.core.ConfigHelper;
import com.thinkit.bigdata.core.feature.orm.mybatis.Page;
import com.thinkit.bigdata.core.util.DateFormatUtil;
import com.thinkit.bigdata.core.util.TaskUtil;
import com.thinkit.bigdata.core.util.es.ESUtil;
import com.thinkit.bigdata.web.controller.pubmet.PubMethod;
import com.thinkit.bigdata.web.coremet.SystemStatic;
import com.thinkit.bigdata.web.dao.sec.SysGroupMapper;
import com.thinkit.bigdata.web.model.BaseEntity;
import com.thinkit.bigdata.web.model.config.SysArea;
import com.thinkit.bigdata.web.model.es.audioEs.VoiceInfoDto;
import com.thinkit.bigdata.web.model.result.Constants;
import com.thinkit.bigdata.web.model.result.HtmlResult;
import com.thinkit.bigdata.web.model.sec.SysGroup;
import com.thinkit.bigdata.web.model.sec.SysGroupExample;
import com.thinkit.bigdata.web.model.sec.User;
import com.thinkit.bigdata.web.service.config.AreaService;
import com.thinkit.bigdata.web.service.sec.GroupService;
import com.thinkit.bigdata.web.service.statistics.PhoneStatisticsServer;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 *
 * Created by hccl on 2018/10/30.
 */
@Service
public class PhoneStatisticsServerImpl implements PhoneStatisticsServer {

    private static Logger logger = Logger.getLogger(PhoneStatisticsServerImpl.class);

    @Resource
    private ESUtil esUtil;

    @Resource
    private AreaService areaService;

    @Resource
    private SysGroupMapper groupMapper;

    @Resource
    protected GroupService groupService;

    @Override
    public Map<String, List<Map<String, String>>> getPhoneQuery(HttpServletRequest request, String type) throws Exception {
        Map<String, List<Map<String, String>>> result = new HashMap<>();
        List<Map<String, String>> resultList = new ArrayList<>();
        List<Map<String, String>> countList = new ArrayList<>();
        Map<String, String> countMap = new HashMap<>();
        String provinceCode = request.getParameter("provinceCode");
        String groupId = request.getParameter("groupId");
        String seatNum = request.getParameter("seatNum");
        String seatName = request.getParameter("seatName");
        String reCallFlag = request.getParameter("reCallFlag");
        String satisfaction = request.getParameter("satisfaction");
        String callStartTime = request.getParameter("callStartTime");
        String callEndTime = request.getParameter("callEndTime");
        Integer pageNum = null;
        Integer pageSize = null;
        int count;
        if ("search".equals(type)) {
            pageNum = Integer.parseInt(request.getParameter("pageNum"));//起始页
            pageSize = Integer.parseInt(request.getParameter("pageSize"));//每页条数
        }
        //省份
        if (
                Strings.isNullOrEmpty(provinceCode)
                        ||
                (Strings.isNullOrEmpty(groupId) && Strings.isNullOrEmpty(seatName) && Strings.isNullOrEmpty(seatNum))
        ) {
            List<String> proCodes;
            if (Strings.isNullOrEmpty(provinceCode)) {
                Map<String, List<String>> map = PubMethod.getProList(areaService, pageNum, pageSize);
                proCodes = map.get("list");
                count = proCodes.size();

            } else {
                proCodes = new ArrayList<>(PubMethod.strToJson(provinceCode).keySet());
                count = proCodes.size();
                if (pageNum != null) {
                    proCodes.clear();
                    int start = pageNum * pageSize;
                    int end = (pageNum + 1) * pageSize;
                    List<String> proList = new ArrayList<>(PubMethod.strToJson(provinceCode).keySet());
                    for (int i = start; i < end && i < proList.size(); i++) {
                        proCodes.add(proList.get(i));
                    }
                }
            }
            for (String proCode : proCodes) {
                Map<String, String> resultMap = new HashMap<>();
                resultMap.put("provinceCode", proCode);
                resultMap.put("groupId", "");
                resultMap.put("seatNum", "");
                resultMap.put("callStartTime", callStartTime);
                resultMap.put("callEndTime", callEndTime);
                //话务量
                resultMap.put("phoneCount", staCount(getPhoneProAll(request, proCode)).toString());
                //呼入量
                resultMap.put("callInCount", callInCount(getPhoneProAll(request, proCode)).toString());
                //呼入量
                resultMap.put("callOutCount", callOutCount(getPhoneProAll(request, proCode)).toString());
                //通话总时长(时分秒)
                Double holdDur = holdDurGet(getPhoneProAll(request, proCode));
                resultMap.put("holdDur", holdDurCount(holdDur));
                //平均通话时长(时分秒)
                resultMap.put("averageDur", averageDurCount(holdDur, Integer.parseInt(resultMap.get("phoneCount"))));
                //重复来电
                resultMap.put("reCallFlag", reCallFlagCount(getPhoneProAll(request, proCode), reCallFlag).toString());
                //非常满意
                resultMap.put("satVeryYes", satCount(getPhoneProAll(request, proCode), satisfaction, 1).toString());
                //满意
                resultMap.put("satYes", satCount(getPhoneProAll(request, proCode), satisfaction, 2).toString());
                //不满意
                resultMap.put("satNo", satCount(getPhoneProAll(request, proCode), satisfaction, 3).toString());
                //未评价
                resultMap.put("satNull", satCount(getPhoneProAll(request, proCode), satisfaction, 4).toString());
                resultList.add(resultMap);
            }
            countMap.put("count", Integer.toString(count));
            countList.add(countMap);
            result.put("countList", countList);
            result.put("resultList", resultList);
            return result;
        }
        //班组为全部
        if (!Strings.isNullOrEmpty(groupId) && "all".equals(groupId) && Strings.isNullOrEmpty(seatName) && Strings.isNullOrEmpty(seatNum)) {
            Map<String, List<String>> map = getGroupIdList(provinceCode, pageNum, pageSize);
            List<String> groudIds = map.get("list");
            count = Integer.parseInt(map.get("count").get(0));
            for (String group : groudIds) {
                Map<String, String> resultMap = new HashMap<>();
                SysGroup sysGroup = groupMapper.selectByPrimaryKey(Long.parseLong(group));
                SysArea area = areaService.selectByPrimaryKey(Integer.parseInt(sysGroup.getAreaid().toString()));
                resultMap.put("provinceCode", area.getCode());
                resultMap.put("groupId", group);
                resultMap.put("seatNum", "");
                resultMap.put("callStartTime", callStartTime);
                resultMap.put("callEndTime", callEndTime);
                //话务量
                resultMap.put("phoneCount", staCount(getPhoneGroupAll(request, group)).toString());
                //呼入量
                resultMap.put("callInCount", callInCount(getPhoneGroupAll(request, group)).toString());
                //呼入量
                resultMap.put("callOutCount", callOutCount(getPhoneGroupAll(request, group)).toString());
                //通话总时长(时分秒)
                Double holdDur = holdDurGet(getPhoneGroupAll(request, group));
                resultMap.put("holdDur", holdDurCount(holdDur));
                //平均通话时长(时分秒)
                resultMap.put("averageDur", averageDurCount(holdDur, Integer.parseInt(resultMap.get("phoneCount"))));
                //重复来电
                resultMap.put("reCallFlag", reCallFlagCount(getPhoneGroupAll(request, group), reCallFlag).toString());
                //非常满意
                resultMap.put("satVeryYes", satCount(getPhoneGroupAll(request, group), satisfaction, 1).toString());
                //满意
                resultMap.put("satYes", satCount(getPhoneGroupAll(request, group), satisfaction, 2).toString());
                //不满意
                resultMap.put("satNo", satCount(getPhoneGroupAll(request, group), satisfaction, 3).toString());
                //未评价
                resultMap.put("satNull", satCount(getPhoneGroupAll(request, group), satisfaction, 4).toString());
                resultList.add(resultMap);
            }
            countMap.put("count", Integer.toString(count));
            countList.add(countMap);
            result.put("countList", countList);
            result.put("resultList", resultList);
            return result;
        }
        //班组为具体
        if (!Strings.isNullOrEmpty(groupId) && !"all".equals(groupId) && Strings.isNullOrEmpty(seatName) && Strings.isNullOrEmpty(seatNum)) {
            Map<String, List<String>> map = getSeatNumListByEs(provinceCode, Long.parseLong(groupId), pageNum, pageSize);
            List<String> seatIds = map.get("list");
            count = Integer.parseInt(map.get("count").get(0));
            for (String seatId : seatIds) {
                Map<String, String> resultMap = new HashMap<>();
                List<VoiceInfoDto> userList =  getVoiceBySeatIdAndName(seatId, null, groupId);
                if (userList == null || userList.isEmpty()) {
                    resultMap.put("provinceCode", "");
                } else {
                    resultMap.put("provinceCode", userList.get(0).getProvinceCode());
                }
                resultMap.put("groupId", groupId);
                resultMap.put("seatNum", seatId);
                resultMap.put("callStartTime", callStartTime);
                resultMap.put("callEndTime", callEndTime);
                //话务量
                resultMap.put("phoneCount", staCount(getPhoneSeatAll(request, seatId)).toString());
                //呼入量
                resultMap.put("callInCount", callInCount(getPhoneSeatAll(request, seatId)).toString());
                //呼入量
                resultMap.put("callOutCount", callOutCount(getPhoneSeatAll(request, seatId)).toString());
                //通话总时长(时分秒)
                Double holdDur = holdDurGet(getPhoneSeatAll(request, seatId));
                resultMap.put("holdDur", holdDurCount(holdDur));
                //平均通话时长(时分秒)
                resultMap.put("averageDur", averageDurCount(holdDur, Integer.parseInt(resultMap.get("phoneCount"))));
                //重复来电
                resultMap.put("reCallFlag", reCallFlagCount(getPhoneSeatAll(request, seatId), reCallFlag).toString());
                //非常满意
                resultMap.put("satVeryYes", satCount(getPhoneSeatAll(request, seatId), satisfaction, 1).toString());
                //满意
                resultMap.put("satYes", satCount(getPhoneSeatAll(request, seatId), satisfaction, 2).toString());
                //不满意
                resultMap.put("satNo", satCount(getPhoneSeatAll(request, seatId), satisfaction, 3).toString());
                //未评价
                resultMap.put("satNull", satCount(getPhoneSeatAll(request, seatId), satisfaction, 4).toString());
                resultList.add(resultMap);
            }
            countMap.put("count", Integer.toString(count));
            countList.add(countMap);
            result.put("countList", countList);
            result.put("resultList", resultList);
            return result;
        }
        //坐席工号不为空 || 坐席姓名不为空
        if (!Strings.isNullOrEmpty(seatNum) || Strings.isNullOrEmpty(seatName)) {
            count = 1;
            Map<String, String> resultMap = new HashMap<>();
            List<VoiceInfoDto> userList =  getVoiceBySeatIdAndName(seatNum, seatName, groupId);
            if (userList == null || userList.isEmpty()) {
                resultMap.put("provinceCode", "");
            } else {
                resultMap.put("provinceCode", userList.get(0).getProvinceCode());
            }
            resultMap.put("groupId", groupId);
            resultMap.put("seatNum", seatNum);
            resultMap.put("callStartTime", callStartTime);
            resultMap.put("callEndTime", callEndTime);
            //话务量
            resultMap.put("phoneCount", staCount(getPhoneSeatIdNumAll(request)).toString());
            //呼入量
            resultMap.put("callInCount", callInCount(getPhoneSeatIdNumAll(request)).toString());
            //呼入量
            resultMap.put("callOutCount", callOutCount(getPhoneSeatIdNumAll(request)).toString());
            //通话总时长(时分秒)
            Double holdDur = holdDurGet(getPhoneSeatIdNumAll(request));
            resultMap.put("holdDur", holdDurCount(holdDur));
            //平均通话时长(时分秒)
            resultMap.put("averageDur", averageDurCount(holdDur, Integer.parseInt(resultMap.get("phoneCount"))));
            //重复来电
            resultMap.put("reCallFlag", reCallFlagCount(getPhoneSeatIdNumAll(request), reCallFlag).toString());
            //非常满意
            resultMap.put("satVeryYes", satCount(getPhoneSeatIdNumAll(request), satisfaction, 1).toString());
            //满意
            resultMap.put("satYes", satCount(getPhoneSeatIdNumAll(request), satisfaction, 2).toString());
            //不满意
            resultMap.put("satNo", satCount(getPhoneSeatIdNumAll(request), satisfaction, 3).toString());
            //未评价
            resultMap.put("satNull", satCount(getPhoneSeatIdNumAll(request), satisfaction, 4).toString());
            resultList.add(resultMap);
            countMap.put("count", Integer.toString(count));
            countList.add(countMap);
            result.put("countList", countList);
            result.put("resultList", resultList);
            return result;
        }
        return result;
    }

    @Override
    public List<VoiceInfoDto> getPhoneDetailData(HttpServletRequest request) throws InvocationTargetException, IllegalAccessException {
        List<VoiceInfoDto> infos = new ArrayList<>();
        String provinceCode = request.getParameter("provinceCode");
        String groupId = request.getParameter("groupId");
        String seatNum = request.getParameter("seatNum");
        String seatName = request.getParameter("seatName");
        //省份
        if (
                Strings.isNullOrEmpty(provinceCode)
                        ||
                        (Strings.isNullOrEmpty(groupId) && Strings.isNullOrEmpty(seatName) && Strings.isNullOrEmpty(seatNum))
        ) {
            List<String> proCodes;
            if (Strings.isNullOrEmpty(provinceCode)) {
                Map<String, List<String>> map = PubMethod.getProList(areaService, null, null);
                proCodes = map.get("list");
            } else {
                proCodes = new ArrayList<>(PubMethod.strToJson(provinceCode).keySet());
            }
            for (String proCode : proCodes) {
                BoolQueryBuilder boolQuery = getPhoneProAll(request, proCode);
                //总条数
                Integer sum = SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, boolQuery);
                //单词查询条数
                int excleMax = ConfigHelper.getInt("export.data.sheet.max.number", 1000);
                List<Integer> pageTout = TaskUtil.formatSum(sum, excleMax);//todo最后一个数字需要特殊处理:6022
                String[] includes = new String[]
                        {
                                "serialNumber",
                                "voiceInfo"
                        };
                for (Integer aPageTout : pageTout) {
                    List<String> docList = SystemStatic.crud.queryMapQBuilderRetRuleAndWork(
                            SystemStatic.AUDIO_ES_INDEX,
                            SystemStatic.AUDIO_ES_TYPE,
                            aPageTout,
                            excleMax,
                            boolQuery,
                            "",
                            "",
                            includes
                    );
                    if (docList.isEmpty()) continue;
                    infos.addAll(esUtil.formatModel(docList));
                }
            }
            return infos;
        }
        //班组为全部
        if (!Strings.isNullOrEmpty(groupId) && "all".equals(groupId) && Strings.isNullOrEmpty(seatName) && Strings.isNullOrEmpty(seatNum)) {
            Map<String, List<String>> map = getGroupIdList(provinceCode, null, null);
            List<String> groudIds = map.get("list");
            for (String group : groudIds) {
                BoolQueryBuilder boolQuery = getPhoneGroupAll(request, group);
                //总条数
                Integer sum = SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, boolQuery);
                //单词查询条数
                int excleMax = ConfigHelper.getInt("export.data.sheet.max.number", 1000);
                List<Integer> pageTout = TaskUtil.formatSum(sum, excleMax);//todo最后一个数字需要特殊处理:6022
                String[] includes = new String[]
                        {
                                "serialNumber",
                                "voiceInfo"
                        };
                for (Integer aPageTout : pageTout) {
                    List<String> docList = SystemStatic.crud.queryMapQBuilderRetRuleAndWork(
                            SystemStatic.AUDIO_ES_INDEX,
                            SystemStatic.AUDIO_ES_TYPE,
                            aPageTout,
                            excleMax,
                            boolQuery,
                            "",
                            "",
                            includes
                    );
                    if (docList.isEmpty()) continue;
                    infos.addAll(esUtil.formatModel(docList));
                }
            }
            return infos;

        }
        //班组为具体
        if (!Strings.isNullOrEmpty(groupId) && !"all".equals(groupId) && Strings.isNullOrEmpty(seatName) && Strings.isNullOrEmpty(seatNum)) {
            Map<String, List<String>> map = getSeatNumListByEs(provinceCode, Long.parseLong(groupId), null, null);
            List<String> seatIds = map.get("list");
            for (String seatId : seatIds) {
                BoolQueryBuilder boolQuery = getPhoneSeatAll(request, seatId);
                //总条数
                Integer sum = SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, boolQuery);
                //单词查询条数
                int excleMax = ConfigHelper.getInt("export.data.sheet.max.number", 1000);
                List<Integer> pageTout = TaskUtil.formatSum(sum, excleMax);//todo最后一个数字需要特殊处理:6022
                String[] includes = new String[]
                        {
                                "serialNumber",
                                "voiceInfo"
                        };
                for (Integer aPageTout : pageTout) {
                    List<String> docList = SystemStatic.crud.queryMapQBuilderRetRuleAndWork(
                            SystemStatic.AUDIO_ES_INDEX,
                            SystemStatic.AUDIO_ES_TYPE,
                            aPageTout,
                            excleMax,
                            boolQuery,
                            "",
                            "",
                            includes
                    );
                    if (docList.isEmpty()) continue;
                    infos.addAll(esUtil.formatModel(docList));
                }
            }
            return infos;
        }
        //坐席工号不为空 || 坐席姓名不为空
        if (!Strings.isNullOrEmpty(seatNum) || Strings.isNullOrEmpty(seatName)) {
            BoolQueryBuilder boolQuery = getPhoneSeatIdNumAll(request);
            //总条数
            Integer sum = SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, boolQuery);
            //单词查询条数
            int excleMax = ConfigHelper.getInt("export.data.sheet.max.number", 1000);
            List<Integer> pageTout = TaskUtil.formatSum(sum, excleMax);//todo最后一个数字需要特殊处理:6022
            String[] includes = new String[]
                    {
                            "serialNumber",
                            "voiceInfo"
                    };
            for (Integer aPageTout : pageTout) {
                List<String> docList = SystemStatic.crud.queryMapQBuilderRetRuleAndWork(
                        SystemStatic.AUDIO_ES_INDEX,
                        SystemStatic.AUDIO_ES_TYPE,
                        aPageTout,
                        excleMax,
                        boolQuery,
                        "",
                        "",
                        includes
                );
                if (docList.isEmpty()) continue;
                infos.addAll(esUtil.formatModel(docList));
            }
        }
        return infos;
    }

    @Override
    public HtmlResult getPhoneCount(HttpServletRequest request) throws Exception {
        String seatNum = request.getParameter("seatNum");
        String seatName = request.getParameter("seatName");
        String groupId = request.getParameter("groupId");
        List<VoiceInfoDto> docList =  getVoiceBySeatIdAndName(seatNum, seatName, groupId);
        if (docList == null || docList.isEmpty()) {
            return HtmlResult.failure("统计的人员不存在");
        }
        Map<String, List<Map<String, String>>> result = getPhoneQuery(request, "search");
        List<Map<String, String>> resultList = result.get("resultList");
        return HtmlResult.success(resultList, Integer.parseInt(result.get("countList").get(0).get("count")));
    }

    private List<VoiceInfoDto> getVoiceBySeatIdAndName(String seatNum, String seatName, String groupId) throws Exception {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        String[] includes = new String[]{"serialNumber", "voiceInfo"};
        if (!Strings.isNullOrEmpty(seatNum)) {
            boolQuery.must(QueryBuilders.matchQuery("voiceInfo.seatId", seatNum));
        }
        if (!Strings.isNullOrEmpty(seatName)) {
            boolQuery.must(QueryBuilders.matchQuery("voiceInfo.seatName", seatName));
        }
        if (!Strings.isNullOrEmpty(groupId) && !"all".equals(groupId)) {
            boolQuery.must(QueryBuilders.matchQuery("voiceInfo.groupId", groupId));
        }
        List<String> docList = SystemStatic.crud.queryMapQBuilderRetRuleAndWork(
                SystemStatic.AUDIO_ES_INDEX,
                SystemStatic.AUDIO_ES_TYPE,
                0,
                1,
                boolQuery,
                "",
                "",
                includes
        );
        return esUtil.formatModel(docList);
    }

    //根据省份获取坐席班组
    private Map<String, List<String>> getGroupIdList(String provinceCode, Integer pageNum, Integer pageSize) {
        Map<String, List<String>> map = new HashMap<>();
        List<String> queryList = new ArrayList<>();
        Session session = SecurityUtils.getSubject().getSession();
        User user = (User) session.getAttribute(Constants.SESSION_USER_INFO);
        int userIdentity = (Integer) session.getAttribute("userIdentity");
        if (BaseEntity.USERIDENTITY_ZJ == userIdentity) {//质检员
            List<SysGroup> seatGroupList = groupService.selectSeatGroupByQcGroupId(user.getGroupid(), user.getId());
            for (SysGroup group : seatGroupList) {
                queryList.add(group.getId().toString());
            }
            map.put("count", Collections.singletonList(seatGroupList.size() + ""));
            if (pageNum != null) {
                Page<SysGroup> page = new Page<>(pageNum + 1, pageSize);
                seatGroupList = groupService.selectSeatGroupByQcGroupId(page, user.getGroupid(), user.getId());
                queryList.clear();
                for (SysGroup group : seatGroupList) {
                    queryList.add(group.getId().toString());
                }
                map.put("count", Collections.singletonList(page.getTotalCount() + ""));
            }
            map.put("list", queryList);
        } else {
            SysGroupExample example = new SysGroupExample();
            SysGroupExample.Criteria criteria = example.createCriteria();
            if (!Strings.isNullOrEmpty(provinceCode)) {
                List<Long> ids = new ArrayList<>();
                for (String code : PubMethod.strToJson(provinceCode).keySet()) {
                    ids.add((long)areaService.selectByPrimaryCode(code).getId());
                }
                criteria.andAreaidIn(ids);
            }
            criteria.andTypeEqualTo(0);// type=0为坐席
            List<SysGroup> groups;
            if (pageNum != null) {
                Page<SysGroup> page = new Page<>(pageNum + 1, pageSize);
                groups = groupMapper.selectByExample(page, example);
                map.put("count", Collections.singletonList(page.getTotalCount() + ""));
            } else {
                groups = groupMapper.selectByExample(example);
                map.put("count", Collections.singletonList(groups.size() + ""));
            }
            for (SysGroup group : groups) {
                queryList.add(group.getId().toString());
            }
            map.put("list", queryList);
        }
        return map;
    }

    //根据坐席班组获取坐席工号
    private Map<String, List<String>> getSeatNumListByEs(String provinceCode, Long groupId, Integer pageNum, Integer pageSize) {
        Map<String, List<String>> map = new HashMap<>();
        List<String> queryList = new ArrayList<>();
        BoolQueryBuilder boolQuery = new BoolQueryBuilder();
        PubMethod.formatPro(provinceCode, boolQuery);
        boolQuery.must(QueryBuilders.matchQuery("voiceInfo.groupId", groupId));
        Terms terms = SystemStatic.crud.getTermsNum(
                SystemStatic.AUDIO_ES_INDEX,
                SystemStatic.AUDIO_ES_TYPE,
                boolQuery,
                "seats",
                "voiceInfo.seatId"
        );
        for (Terms.Bucket entry : terms.getBuckets()) {
            String key = entry.getKey().toString();                    // bucket key
            long docCount = entry.getDocCount();            // Doc count
            logger.info("key [{}], doc_count [{}]");
            logger.info(key);
            logger.info(docCount);
            queryList.add(key);
        }
        if (pageNum == null) {
            map.put("list", queryList);
            map.put("count", Collections.singletonList(queryList.size() + ""));
            return map;
        }
        int start = pageNum * pageSize;
        int end = (pageNum + 1) * pageSize;
        List<String> pageList = new ArrayList<>();
        for (int i = start; i < end && i < queryList.size(); i++) {
            pageList.add(queryList.get(i));
        }
        map.put("list", pageList);
        map.put("count", Collections.singletonList(queryList.size() + ""));
        return map;
    }

    //省份查询条件
    private BoolQueryBuilder getPhoneProAll(HttpServletRequest request, String query) {
        String provinceCode = request.getParameter("provinceCode");
        BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
        Map<String, List<String>> proMap = PubMethod.strToJson(provinceCode);
        //归属地为空时，为直辖市
        if (!proMap.get(query).isEmpty()) {
            BoolQueryBuilder citySQ = new BoolQueryBuilder();
            for (String city : proMap.get(query)) {
                citySQ.should(QueryBuilders.matchQuery("voiceInfo.customerloc", city));
            }
            queryBuilder.must(citySQ);
        }
        queryBuilder.must(QueryBuilders.matchQuery("voiceInfo.provinceCode", query));
        getPhoneQ(request, queryBuilder);
        return queryBuilder;
    }

    //班组查询条件
    private BoolQueryBuilder getPhoneGroupAll(HttpServletRequest request, String query) {
        String provinceCode = request.getParameter("provinceCode");
        BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
        PubMethod.formatPro(provinceCode, queryBuilder);
        queryBuilder.must(QueryBuilders.matchQuery("voiceInfo.groupId", query));
        getPhoneQ(request, queryBuilder);
        return queryBuilder;
    }

    //坐席查询条件
    private BoolQueryBuilder getPhoneSeatAll(HttpServletRequest request, String query) {
        String provinceCode = request.getParameter("provinceCode");
        String groupId = request.getParameter("groupId");
        BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
        PubMethod.formatPro(provinceCode, queryBuilder);
        queryBuilder.must(QueryBuilders.matchQuery("voiceInfo.groupId", groupId));
        queryBuilder.must(QueryBuilders.matchQuery("voiceInfo.seatId", query));
        getPhoneQ(request, queryBuilder);
        return queryBuilder;
    }

    //坐席工号/作息姓名查询条件
    private BoolQueryBuilder getPhoneSeatIdNumAll(HttpServletRequest request) {
        String provinceCode = request.getParameter("provinceCode");
        String groupId = request.getParameter("groupId");
        String seatNum = request.getParameter("seatNum");
        String seatName = request.getParameter("seatName");
        BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
        PubMethod.formatPro(provinceCode, queryBuilder);
        queryBuilder.must(QueryBuilders.matchQuery("voiceInfo.groupId", groupId));
        if (!Strings.isNullOrEmpty(seatNum)) {
            queryBuilder.must(QueryBuilders.matchQuery("voiceInfo.seatId", seatNum));
        }
        if (!Strings.isNullOrEmpty(seatName)) {
            queryBuilder.must(QueryBuilders.matchQuery("voiceInfo.seatName", seatName));
        }
        getPhoneQ(request, queryBuilder);
        return queryBuilder;
    }

    //其余查询条件
    private void getPhoneQ(HttpServletRequest request, BoolQueryBuilder queryBuilder) {
        String customerNum = request.getParameter("customerNum");
        String reCallFlag = request.getParameter("reCallFlag");
        String satisfaction = request.getParameter("satisfaction");
        String callStartTime = request.getParameter("callStartTime");
        String callEndTime = request.getParameter("callEndTime");
        //数据权限
        esUtil.formatQ(queryBuilder, null);
        if (!Strings.isNullOrEmpty(customerNum)) {
            queryBuilder.must(QueryBuilders.wildcardQuery("voiceInfo.customerNum", "*" + customerNum + "*"));
        }
        if (!Strings.isNullOrEmpty(reCallFlag)) {
            queryBuilder.must(QueryBuilders.matchQuery("voiceInfo.reCallFlag", reCallFlag));
        }
        if (!Strings.isNullOrEmpty(satisfaction)) {
            queryBuilder.must(QueryBuilders.matchQuery("voiceInfo.satisfaction", satisfaction));
        }
        if (!Strings.isNullOrEmpty(callStartTime)) {
            PubMethod.formatTime(queryBuilder, callStartTime, callEndTime);
        }
    }

    //话务量
    private static Integer staCount(BoolQueryBuilder queryBuilder) {
        return SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, queryBuilder);
    }

    //呼入量
    private static Integer callInCount(BoolQueryBuilder queryBuilder) {
        queryBuilder.must(QueryBuilders.matchQuery("voiceInfo.callDirection", 0));
        return SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, queryBuilder);
    }

    //呼出量
    private static Integer callOutCount(BoolQueryBuilder queryBuilder) {
        queryBuilder.must(QueryBuilders.matchQuery("voiceInfo.callDirection", 1));
        return SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, queryBuilder);
    }

    //通话总时长
    private static Double holdDurGet(BoolQueryBuilder queryBuilder) {
        return SystemStatic.crud.getAggSum(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, queryBuilder, "holdDuration_sum", "voiceInfo.holdDuration");
    }

    //通话总时长(时分秒)
    private static String holdDurCount(Double holdDur) {
        return DateFormatUtil.secToTime(holdDur);
    }

    //平均通话时长(时分秒)
    private static String averageDurCount(Double holdDur, int phoneCount) {
        if (phoneCount == 0) {
            return DateFormatUtil.secToTime(0);
        }
        return DateFormatUtil.secToTime(holdDur / phoneCount);
    }

    //重复来电
    private static Integer reCallFlagCount(BoolQueryBuilder queryBuilder, String reCallFlag) {
        if ("0".equals(reCallFlag)) {
            return 0;
        } else {
            queryBuilder.must(QueryBuilders.matchQuery("voiceInfo.reCallFlag", 1));
        }
        return SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, queryBuilder);
    }

    //非常满意
    private static Integer satCount(BoolQueryBuilder queryBuilder, String satisfaction, Integer sat) {
        if (Strings.isNullOrEmpty(satisfaction)) {
            queryBuilder.must(QueryBuilders.matchQuery("voiceInfo.satisfaction", sat));
        } else {
            if (!sat.toString().equals(satisfaction)) {
                return 0;
            } else {
                queryBuilder.must(QueryBuilders.matchQuery("voiceInfo.satisfaction", satisfaction));
            }
        }
        return SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, queryBuilder);
    }



}
